use regex::Regex;

pub fn retire_time(time: &str, tp: &str) -> String {
    let re = Regex::new(r"(\d{4})-(\d{2})").unwrap();
    let caps = re.captures(time).unwrap();
    let year = caps.get(1).unwrap().as_str().parse::<i32>().unwrap();
    let month = caps.get(2).unwrap().as_str().parse::<i32>().unwrap();
    
    if tp == "男职工" {
        cal_man(year, month)
    } else {
        let re = Regex::new(r"原法定退休年龄(\d{2})周岁女职工").unwrap();
        let caps = re.captures(tp).unwrap();
        let retire_year = caps.get(1).unwrap().as_str().parse::<i32>().unwrap();
        cal_wo(year, month, retire_year)
    }
}

fn cal_man(year: i32, month: i32) -> String {
    // let addtion_month = if year < 1965 {
    //     0
    // } else if year >= 1977 {
    //     36
    // } else {
    //     ((year - 1965) * 12 + month - 1) / 4+1
    // };

    // let mut retire_year = year + 60+addtion_month/12;
    // let mut retire_month = month  + addtion_month%12;

    // // Correct month overflow
    // if retire_month > 12 {
    //     retire_year += retire_month / 12;
    //     retire_month = retire_month % 12;
    // }

    // let retire_age = 60.0+((addtion_month as f64) / 12.0);
    let (retire_year,retire_month,retire_age,addtion_month)=uni_cal(year,month,1965,1977,36,60,4);
    format!("{}-{:02},{},{}", retire_year, retire_month, format_age(retire_age), addtion_month)
}

fn cal_wo(year: i32, month: i32, retire_age: i32) -> String {
    match retire_age {
        50 => {
            let (retire_year,retire_month,retire_age,addtion_month)=uni_cal(year,month,1975,1984,60,50,2);
            format!("{}-{:02},{},{}", retire_year, retire_month, format_age(retire_age), addtion_month)
        }
        55 => {
            let (retire_year,retire_month,retire_age,addtion_month)=uni_cal(year,month,1970,1981,36,55,4);
            format!("{}-{:02},{},{}", retire_year, retire_month, format_age(retire_age), addtion_month)
        }
        _ => panic!("Invalid retire age"),
        
    }
}

fn format_age(age: f64) -> String {
    if age.fract() == 0.0 {
        format!("{}", age as i32)
    } else {
        format!("{:.2}", age)
    }
}


fn  uni_cal(year:i32,month:i32,start_year:i32,end_year:i32,max_add:i32,origin_year:i32,div:i32)->(i32,i32,f64,i32){
    let addtion_month = if year < start_year {
        0
    } else if year >= end_year {
        max_add
    } else {
        ((year - start_year) * 12 + month - 1) / div+1
    };

    let mut retire_year = year + origin_year+addtion_month/12;
    let mut retire_month = month  + addtion_month%12;

    // Correct month overflow
    if retire_month > 12 {
        retire_year += retire_month / 12;
        retire_month = retire_month % 12;
    }

    let retire_age = (origin_year as f64)+((addtion_month as f64) / 12.0);
    (retire_year,retire_month,retire_age,addtion_month)
}